package com.csii.autocode.utils;

import cn.hutool.core.util.RandomUtil;

import java.io.IOException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class NonceUtils {

    private static final String[] SPACES = new String[]{"0", "00", "0000", "00000000"};

    private static Date lastTime;

    private static int counter = 0;

    //生成指定长度的随机字符串
    public static String randomString(int paramInt) {
        return RandomUtil.randomNumbers(paramInt);
    }

    //生成强随机数（Int）
    public static int randomInt() {
        return (new SecureRandom()).nextInt();
    }

    //把Int类型转换为16进制String类型
    public static String randomHexInt() {
        return Integer.toHexString(randomInt());
    }

    //生成强随机数（Long）
    public static long randomLong() {
        return (new SecureRandom()).nextLong();
    }

    //把Long类型转换为16进制String类型
    public static String randomHexLong() {
        return Long.toHexString(randomLong());
    }

    //生成随机UUID
    public static String randomUUID() {
        return UUID.randomUUID().toString();
    }

    //把日期格式为字符串
    public static String currentTimestamp() {
        Date date = new Date();
        return  new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(date);
    }

    //获取当前时间
    public static long currentMills() {
        return System.currentTimeMillis();
    }

    //把Long类型的日期转换为String类型
    public static String currentHexMills() {
        return Long.toHexString(currentMills());
    }

    //
    public static synchronized String getCounter() {
        Date date = new Date();
        if (date.equals(lastTime)) {
            counter++;
        } else {
            lastTime = date;
            counter = 0;
        }
        return Integer.toHexString(counter);
    }

    public static String format(String paramString, int paramInt) {
        int i = paramInt - paramString.length();
        StringBuilder stringBuilder = new StringBuilder();
        while (i >= 8) {
            stringBuilder.append(SPACES[3]);
            i -= 8;
        }
        for (byte j = 2; j >= 0; j--) {
            if ((i & 1 << j) != 0)
                stringBuilder.append(SPACES[j]);
        }
        stringBuilder.append(paramString);
        return stringBuilder.toString();
    }

    public static void main(String[] args) throws IOException {
        System.out.println(randomLong() + getCounter());
    }
}
